<script lang="ts" setup>
const dialogVisible = ref(false)

const postersState = reactive({
  designId: '',
  fileName: '',
  thumbUrls: [] as string[],
  sourceUrls: [] as string[]
})

const handleClose = () => {
  dialogVisible.value = false
}

const handleDownload = () => {
  postersState.sourceUrls.forEach((url) => {
    // 创建隐藏的可下载链接
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none' // 防止影响页面
    iframe.style.height = '0' // 防止影响页面
    iframe.src = url
    document.body.appendChild(iframe) // 这一行必须，iframe挂在到dom树上才会发请求
    // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
    setTimeout(() => {
      iframe.remove()
    }, 1000)
  })
}

const saveToMaterialCenter = () => {}

type PosterRes = {
  width: number
  height: number
  cktMessage: boolean
  'create-time': Date
  'current-page': number
  'design-id': string
  'design-name': string
  'download-format': number
  'have-MP4': number
  'have-gif': number
  'is-ppt': number
  kind: number
  'kind-id': number
  'kind-name': string
  page: number
  price: number
  'price-font': number
  'price-material': number
  'source-urls': string[]
  'template-id': number
  'thumb-exp': number | undefined
  'thumb-urls': string[]
  unit: string
}

type PosterFailRes = {
  code: string
  data: { design_id: string }
  msg: string
  type: string
}

const handleChuangkitCompleteSuccess = (res: PosterRes) => {
  postersState.designId = res['design-id']
  postersState.fileName = res['design-name']
  postersState.thumbUrls = res['thumb-urls']
  postersState.sourceUrls = res['source-urls']

  console.log('传入参数：', res)
  console.log('当前状态：', postersState)

  dialogVisible.value = true
}

const handleChuangkitCompleteNeedPay = (res: PosterFailRes) => {
  console.log('需要支付', res)
}

// 创客贴保存事件
const win = window as any
win.chuangkitComplete = (res: any) => {
  console.log('chuangkitComplete', res)

  if (res.kind && res.kind === 2) handleChuangkitCompleteSuccess(res as PosterRes)
  else if (res.type && res.type === 'postposition')
    handleChuangkitCompleteNeedPay(res as PosterFailRes)
}
</script>

<template>
  <el-dialog v-model="dialogVisible" title="保存" width="70%" :before-close="handleClose">
    <div class="flex flex-wrap justify-center gap-3">
      <div v-for="thumbUrl in postersState.thumbUrls" :key="thumbUrl" class="h-52 border">
        <el-image class="h-full" :src="thumbUrl" />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <!-- <el-button type="primary" @click="saveToMaterialCenter"> 保存到素材中心 </el-button> -->
        <el-button type="primary" @click="handleDownload">下载到本地</el-button>
      </span>
    </template>
  </el-dialog>
</template>
